<template>
  <div>
    <template v-for="item in list" :key="item.path">
      <template v-if="!item.children.length || item.meta?.single || item.meta?.hideChildren">
        <t-menu-item v-if="item.href" :name="item.path" :value="getPath(item)" @click="openHref(item.href[0])">
          <template #icon>
            <lg-icon :value="item.icon" class="lg-soar-menu-icon t-icon" />
          </template>
          {{ item.title }}
        </t-menu-item>
        <t-menu-item v-else :name="item.path" :value="getPath(item)" :to="item.path">
          <template #icon>
            <lg-icon :value="item.icon" class="lg-soar-menu-icon t-icon" />
          </template>
          {{ item.title }}
        </t-menu-item>
      </template>
      <t-submenu v-else :name="item.path" :value="item.path" :title="item.title">
        <template #icon>
          <lg-icon :value="item.icon" class="lg-soar-menu-icon t-icon" />
        </template>
        <menu-content v-if="item.children" :nav-data="item.children" />
      </t-submenu>
    </template>
  </div>
</template>

<script setup lang="ts">
import type { PropType } from 'vue';
import { computed } from 'vue';
import type { MenuRoute } from '@/types/interface';
import { getActive } from '@/router';
import { LgIcon } from '@/soar';

const props = defineProps({
  navData: {
    type: Array as PropType<MenuRoute[]>,
    default: () => [],
  },
});

const active = computed(() => getActive());
const list = computed(() => getMenuList(props.navData));

type ListItemType = MenuRoute & { icon?: any; href: any };

const getMenuList = (list: MenuRoute[]): ListItemType[] => {
  if (!list) {
    return [];
  }
  // 过滤扁平处理
  list = list
    .filter((item) => item.meta?.hidden !== true)
    .flatMap((item) => {
      if (item.meta?.hiddenSelf === true) {
        return (item.children ?? []).filter((item) => item.meta?.hidden !== true);
      }
      return [item];
    });
  // 排序处理
  list.sort((a, b) => (a.meta?.sort ?? 0) - (b.meta?.sort ?? 0));
  // 转换为菜单
  return list.map((item) => {
    return {
      path: item.path.replace(/\/+/g, '/'),
      title: item.meta?.title,
      icon: item.meta?.icon,
      href: getHref(item),
      children: item.meta?.hiddenChildren ? [] : item.children ?? [],
      meta: item.meta,
      redirect: item.redirect,
    };
  });
};

const getHref = (item: MenuRoute) => {
  const { frameSrc, frameBlank } = item.meta;
  if (frameSrc && frameBlank) {
    return frameSrc.match(/(http|https):\/\/([\w.]+\/?)\S*/);
  }
  return null;
};

const getPath = (item) => {
  if (active.value.startsWith(item.path)) {
    return active.value;
  }
  return item.meta?.single ? item.redirect : item.path;
};

const openHref = (url: string) => {
  window.open(url);
};
</script>
